package com.example.experiment_five;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends Activity {
    SharedPreferences preferences;
    SharedPreferences.Editor editor;
    Button write,read,button;
    int count;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.sql);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,DBTest.class);
                startActivity(intent);
            }
        });

        preferences = getSharedPreferences("count",MODE_PRIVATE);
        editor = preferences.edit();
        write = findViewById(R.id.write_data);
        read = findViewById(R.id.read_data);
        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //读取字符串数据
                String time = preferences.getString("time",null);
                //读取SharedPreferences里的count数据
                count = preferences.getInt("count",0);
                String result = time == null ? "您暂时还未写入数据" : "写入时间为："
                        + time + "\n程序以前被使用了" + count + "次。";
                //显示程序以前使用的次数
                Toast.makeText(MainActivity.this,result,Toast.LENGTH_LONG).show();

            }
        });
        write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日" + "hh:mm:ss");
                //存入时间
                editor.putString("time",sdf.format(new Date()));
                //存入数据
                editor.putInt("count", ++count);
                //提交修改
                editor.apply();
            }
        });
    }
}
